package com.axios.controller.servlets;

import com.axios.models.pojo.JsonServer;
import com.axios.service.JsonServerService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/addJsonServer")
public class JsonServerAddServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IOException {
        // 设置响应头允许跨域
        response.setHeader("Access-Control-Allow-Origin", "*");

        // 响应头
        response.setHeader("Access-Control-Allow-Headers", "*");

        // 接收请求的参数
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        String age = request.getParameter("age");

        // 创建对象
        JsonServer jsonServer = new JsonServer(name, sex, Integer.parseInt(age));

        // 执行添加操作
        int count = JsonServerService.add(jsonServer);

        // 判断是否添加成功
        if (count == 0) {
            response.getWriter().write("该学生已存在!");
        } else if (count == -1) {
            response.getWriter().write("添加失败！");
        } else {
            response.getWriter().write("添加成功！");
        }
    }
}
